import api from "../../api/mop";
import { toast, err } from "../../utils/wxapi";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    list: [],
    page: 1,
    size: 20,
    pageTotal: 0,
    cha: "",
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    this.userlist();
  },
  async userlist() {
    try {
      const { page, size, list } = this.data;
      const res = await api.userList({ page, size });
      if (res.respCode === 200) {
        const newlist = JSON.parse(res.source);
        const pageTotal = res.pageTotal;
        this.setData({
          list: list.length > 0 ? list.concat(newlist) : newlist,
          pageTotal,
        });
      }
    } catch (error) {
      err(error);
    }
  },
  pay(e) {
    const userId = e.currentTarget.dataset.item.userId;
    wx.showModal({
      title: "充值",
      editable: true,
      complete: async (res) => {
        if (res.confirm) {
          const amount = res.content;
          if (isNaN(amount)) return toast("请输入数字");
          try {
            const { respCode, msg } = await api.userpay({ userId, amount });
            if (respCode === 200) {
              toast("充值成功");
              this.setData({ page: 1, list: [] });
              this.userlist();
            } else {
              toast(msg);
              err(msg);
            }
          } catch (error) {}
        }
      },
    });
  },
  async query() {
    try {
      const mobile = this.data.cha;
      const res = await api.userList({ data: { mobile } });
      console.log(res);
      if (res.respCode === 200) {
        const list = JSON.parse(res.source);
        this.setData({ list });
      }
    } catch (error) {
      err(error);
    }
  },
  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    const { page, pageTotal, list } = this.data;
    if (list.length >= pageTotal) return toast("以获取全部信息");
    this.setData({ page: page + 1 });
    this.userlist();
  },
});
